package com.kk.base.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
public class ServiceLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

    // 切点表达式，作用于service包下的所有类和所有方法
    @Pointcut("execution(* com.kk.base.service.*.*.*(..))")
    public void pointcut() {

    }

    /**
     * 前置通知
     *
     * @param joinPoint 被调用的方法
     *                  用来打印每个业务层下每个方法被调用的时间，已经方法类型和方法名
     */
    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        String target = joinPoint.getSignature().getDeclaringTypeName()
                + "." + joinPoint.getSignature().getName();
        logger.info(String.format("调用方法===> [%s]", target));
    }

}
